package com.iweb.service;

import com.common.datasource.DataSourceUtil;

import com.iweb.dao.UserDao;
import com.iweb.dao.UserDaoImpl;
import com.iweb.pojo.User;

import java.util.UUID;

/**
 * @Package: com.iweb.service
 * @ClassName: UserService
 * @Author: lenovo --yang
 * @CreateTime: 2020/8/11 17:17
 * @Description: UserService
 */
public class UserService {
    public User findUser(String type, String account) {
        User user = null;
        // 链接数据库
        DataSourceUtil dataSourceUtil = new DataSourceUtil();
        dataSourceUtil.init();
        // 创建数据库操作对象
        UserDao userDao = new UserDaoImpl(dataSourceUtil.getConnection());
        try {
            // 业务逻辑
//            user = userDao.findUserByUsername(user_name);
            user = userDao.findUser(type,account);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dataSourceUtil.close();
        }
        return user;
    }

    // 添加用户
    public boolean addUser(User user) {
        // 连接数据库
        DataSourceUtil dataSourceUtil = new DataSourceUtil();
        dataSourceUtil.init();
        // 创建数据库操作对象
        UserDao userDao = new UserDaoImpl(dataSourceUtil.getConnection());
        try{
            // 通过账户查询 账户是否已经存在
            User users = userDao.findUserByPhone(user.getUser_phone());
            if(users != null){
                // 用户已经存在
                throw new RuntimeException();
            }
            // 用户不存在
            // 注册用户
            user.setUser_id(UUID.randomUUID().toString()); // 设定主键
            userDao.save(user);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }finally {
            dataSourceUtil.close();
        }
    }

    /* 手机号查单 */
    public User findUserByPhone(String user_phone) {
        User user = null;
        // 链接数据库
        DataSourceUtil dataSourceUtil = new DataSourceUtil();
        dataSourceUtil.init();
        // 创建数据库操作对象
        UserDao userDao = new UserDaoImpl(dataSourceUtil.getConnection());
        try {
            // 业务逻辑
            user = userDao.findUserByPhone(user_phone);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            dataSourceUtil.close();
        }
        return user;
    }
}
